package com.tbit.uqbike.webmanager.util.http;

import com.tbit.uqbike.object.pojo.Task;
import com.tbit.uqbike.webmanager.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author jing
 * @date 2020/8/2410:22
 * @Description:
 */
@Slf4j
public class HttpRequestUtils {


    /**
     * @author jing
     * @date 2020/8/24 11:38
     * @Description: 使用apache的httpclient进行get请求
     */
    public static String doGet(String url, List<NameValuePair> params, Map<String, String> head) {
        HttpClient httpClient = HttpClients.createDefault();
        String result = null;
        HttpResponse response = null;
        URIBuilder uriBuilde = null;
        //设置get请求及请求头
        HttpGet get = new HttpGet();
        setHead(get, head);
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(5000).setSocketTimeout(10000).build();
        get.setConfig(config);
        try {
            uriBuilde = new URIBuilder(url);
            //将请求参数添加到uri中
            if (StringUtils.isNotNull(params)) {
                uriBuilde.addParameters(params);
            }
            get.setURI(uriBuilde.build());
            //发送请求获取响应
            response = httpClient.execute(get);
            //获取响应的实体将之转换成字符串
            result = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            log.error("doGet请求超时", e);
            log.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * @author jing
     * @date 2020/8/24 11:50
     * @Description: 使用apache进行post请求传送json对象，并将传输格式（ContentType）设置为application/json
     */
    public static String doPost(String url, Task task, Map<String, String> head) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = null;
        HttpPost post = new HttpPost(url);
        MultipartFile file = task.getFile();
        HttpResponse httpResponse;
        //设置连接(5秒)和响应超时(10秒)
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();
        try {
            //builder
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            builder.setCharset(Consts.UTF_8);
            post.setConfig(config);
            //将json字符串转换成json对象
            if (StringUtils.isNotNull(file)) {
                String fileName = file.getOriginalFilename();
                // 文件流
                builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            }
            if (StringUtils.isNotEmpty(task.getCustomer())) {
                builder.addTextBody("customer", task.getCustomer());
            }
            builder.addTextBody("terMnos", task.getTerMnos());
            builder.addTextBody("module", task.getModule());
            builder.addTextBody("aTime", String.valueOf(task.getATime()));
            builder.addTextBody("eTime", String.valueOf(task.getETime()));

            //请求设置实体
            post.setEntity(builder.build());
            //设置请求参数和头部文件
            setHead(post, head);
            //执行请求
            httpResponse = httpClient.execute(post);
            //将响应数据转换成字符串
            result = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("doPost请求超时", e);
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return result;
    }

    /**
     * @author jing
     * @date 2020/8/24 11:50
     * @Description: 使用apache进行post请求传送json对象，并将传输格式（ContentType）设置为application/json
     */
    public static String doPost(String url, String data, Map<String, String> head) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = null;
        HttpPost post = new HttpPost(url);
        //设置post请求的entity,将json字符串转换成json对象进行传输
        StringEntity entity;
        HttpResponse httpResponse;
        //设置连接(5秒)和响应超时(10秒)
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(5000).setSocketTimeout(10000).build();
        try {
            post.setConfig(config);
            //将json字符串转换成json对象
            if (StringUtils.isNotNull(data)) {
                entity = new StringEntity(data, "utf8");
                //设置json的数据提交方式
                setEntity(entity);
                //请求设置实体
                post.setEntity(entity);
            }
            //设置请求参数和头部文件
            setHead(post, head);
            //执行请求
            httpResponse = httpClient.execute(post);
            //将响应数据转换成字符串
            result = EntityUtils.toString(httpResponse.getEntity());
        } catch (Exception e) {
            log.error("doPost请求超时", e);
            log.error(e.getMessage(), e);
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return result;
    }

    /**
     * @author jing
     * @date 2020/8/26 19:06
     * @Description: 设置http请求头部消息
     */
    public static void setHead(HttpMessage method, Map<String, String> head) {
        //设置请求参数和头部文件
        method.addHeader("accept", "*/*");
        method.addHeader("connection", "Keep-Alive");
        method.addHeader("user-agent",
                "PostmanRuntime/7.26.5");
        if (StringUtils.isNotEmpty(head)) {
            head.forEach(method::addHeader);
        }
    }


    /**
     * @author jing
     * @date 2020/8/26 19:15
     * @Description: 设置数据提交格式为json格式
     */
    public static void setEntity(StringEntity entity) {
        entity.setContentEncoding("utf8");
        entity.setContentType("application/json");
    }

    public static List<NameValuePair> toNameValuePair(Map<String, String> params) {
        Set<Map.Entry<String, String>> entries = params.entrySet();
        List<NameValuePair> pairList = new ArrayList<>();
        for (Map.Entry<String, String> entry : entries) {
            NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
            pairList.add(pair);
        }
        return pairList;
    }

}

